package api

import (
	"go-weiqi-system/config"
	"go-weiqi-system/internal/models"
	"go-weiqi-system/internal/utils"

	"github.com/gin-gonic/gin"
)

type MyCourseController struct{}

// Index 我的课程列表
func (ctrl *MyCourseController) Index(c *gin.Context) {
	userID, _ := c.Get("user_id")

	var param models.PageParam
	if err := c.ShouldBindQuery(&param); err != nil {
		param.Page = 1
		param.PageSize = 10
	}

	var userCourses []models.UserCourse
	var total int64

	db := config.DB.Model(&models.UserCourse{}).
		Where("user_id = ?", userID).
		Preload("Course")

	db.Count(&total)
	db.Order("id desc").
		Offset(param.GetOffset()).
		Limit(param.GetPageSize()).
		Find(&userCourses)

	utils.Success(c, models.PageResponse{
		List:     userCourses,
		Total:    total,
		Page:     param.GetPage(),
		PageSize: param.GetPageSize(),
	})
}

// CheckPurchased 检查是否已购买某课程
func (ctrl *MyCourseController) CheckPurchased(c *gin.Context) {
	userID, _ := c.Get("user_id")
	courseID := c.Query("course_id")

	if courseID == "" {
		utils.Error(c, "参数错误")
		return
	}

	var count int64
	config.DB.Model(&models.UserCourse{}).
		Where("user_id = ? AND course_id = ?", userID, courseID).
		Count(&count)

	utils.Success(c, gin.H{
		"purchased": count > 0,
	})
}

// Detail 课程详情（已购买的）
func (ctrl *MyCourseController) Detail(c *gin.Context) {
	userID, _ := c.Get("user_id")
	courseID := c.Query("course_id")

	if courseID == "" {
		utils.Error(c, "参数错误")
		return
	}

	var userCourse models.UserCourse
	if err := config.DB.Where("user_id = ? AND course_id = ?", userID, courseID).
		Preload("Course").
		First(&userCourse).Error; err != nil {
		utils.Error(c, "未购买该课程")
		return
	}

	utils.Success(c, userCourse)
}
